package org.linlinjava.litemall.db.util;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @author wj
 * @date 2021/10/12 15:44
 */
public class OssUtil {
    private Logger logger = LoggerFactory.getLogger(OssUtil.class);

    public String uploadFile(String filePath,String folderPath){
        OSS ossClient = new OSSClientBuilder().build(OssConstant.END_POINT, OssConstant.ACCESSKEY_ID, OssConstant.ACCESSKEY_SECRET);
        // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);

        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(OssConstant.BUCKET_NAME, folderPath, inputStream);

        //100年后链接过期
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
        // 生成URL
//        URL url = ossClient.generatePresignedUrl(OssConstant.BUCKET_NAME, folderPath, expiration);



        // 关闭OSSClient。
        ossClient.shutdown();

        //公共读使用
        String publicUrl="https://litemall-admin-001.oss-cn-hangzhou.aliyuncs.com/"+folderPath;
        return publicUrl;

        //私有读使用
//        if(ObjectUtil.isNull(url)){
//            return null;
//        }
//        return url.toString();
        }catch (OSSException oe) {
            logger.error("OSSException: Error Message:{} ,Error Code:{}",oe.getErrorMessage(),oe.getErrorCode());
        } catch (ClientException ce) {
            logger.error("ClientException: Error Message:{}",ce.getErrorMessage());
        }catch (FileNotFoundException ffe) {
            logger.error("FileNotFoundException: Error Message:{}",ffe);
        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
